﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing.Design;
using System.Windows.Forms.Design;
using System.Windows.Forms;
using Microsoft.VisualStudio.Modeling.Diagrams;

namespace DSLFactory.VSCTDesigner
{
    class IDSymbolEditor : UITypeEditor
    {
        private IWindowsFormsEditorService _edService;

        public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            NodeShape shape = context.Instance as NodeShape;
            Command cmd = shape.ModelElement as Command;

            IList<CommandTable> cts = cmd.Store.ElementDirectory.FindElements<CommandTable>();
            if( cts != null && cts.Count > 0 )
            {
                CommandTable ct = cts[0];
                GuidSymbol guidSymbol = ct.Symbols.Find(s => s.Name == cmd.Guid);
                _edService = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));

                ListBox list = new ListBox();
                list.Click += new EventHandler(list_Click);

                if( guidSymbol != null )
                {
                    foreach( IDSymbol id in guidSymbol.IDSymbols )
                    {
                        list.Items.Add(id.Name);
                    }
                }

                try
                {
                    if(cmd is ExternCommand && ct.NativeCommandTable != null )
                    {
                        Guid g = ct.NativeCommandTable.FindSymbolGuid(cmd.Guid);
                        if( g != Guid.Empty )
                        {
                            foreach( var str in ct.NativeCommandTable.GetIDSymbols(g) )
                            {
                                list.Items.Add(str);
                            }
                        }
                    }
                }
                catch { }

                _edService.DropDownControl(list);
                if( list.SelectedIndex >= 0 )
                {
                    string val = (string)list.Items[list.SelectedIndex];
                    return val;
                }
            }
            return base.EditValue(context, provider, value);
        }

        void list_Click(object sender, EventArgs e)
        {
            _edService.CloseDropDown();
        }

        public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context)
        {
            return UITypeEditorEditStyle.DropDown;
        }
    }
}
